package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   使用异步API 获取节点数据内容
 * @author: cww
 * @DateTime: 2020-01-18 11:06
 */

public class ZooKeeperGetDataASyncAPI implements Watcher {
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
    private static ZooKeeper zk = null;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zk = new ZooKeeper("home:2181", 5000, new ZooKeeperGetDataASyncAPI());
        connectedSemaphore.await();
        zk.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.getData(path, true, new IDataCallback(), null);
        zk.setData(path, "456".getBytes(), -1);
        Thread.sleep(50000);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    zk.getData(event.getPath(), true, new IDataCallback(), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

/**
 * 异步回调方法，节点数据内容被改变后服务端将回调该方法
 */
class IDataCallback implements  AsyncCallback.DataCallback {
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        System.out.println("code: " + rc + ", path: " + path + ", ctx: " + ctx + ", data: " + new String(data));
        System.out.println("Czxid: " + stat.getCzxid() + ", Mzxid: " + stat.getMzxid() + ", Version: " + stat.getVersion());
    }
}
